package com.ygou.controller;


import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ygou.pojo.Admininfo;
import com.ygou.pojo.Browfav;
import com.ygou.pojo.Goods;
import com.ygou.pojo.GoodsAppraises;
import com.ygou.pojo.GoodsType;
import com.ygou.pojo.GoodsWithBLOBs;
import com.ygou.pojo.SkuAttrval;
import com.ygou.pojo.Skus;
import com.ygou.pojo.SkusExample;
import com.ygou.pojo.SkusExample.Criteria;
import com.ygou.pojo.Users;
import com.ygou.service.BrowfavService;
import com.ygou.service.GoodsAppraisesService;
import com.ygou.service.SkusService;
import com.ygou.service.impl.GoodServiceImpl;
import com.ygou.service.impl.GoodTypeServiceImpl;
import com.ygou.service.impl.SkuAttrvalServiceImpl;
import com.ygou.service.impl.SkusServiceImpl;
import com.ygou.utils.AppendContentToFile;
import com.ygou.utils.FileUDUtil;


@Controller
@RequestMapping(value="/goods")
@SessionAttributes(value={"typeList","ls"})
public class GoodController{
	@Autowired
	GoodTypeServiceImpl gtService;
	@Autowired
	GoodServiceImpl gService;
	@Autowired
	SkusServiceImpl skuService;
	@Autowired
	SkuAttrvalServiceImpl skuAS;
	@Autowired
	private SkusService skusService;
	@Autowired
	BrowfavService browfavService;
	@Autowired
	private GoodsAppraisesService goodsAppraisesService;
	@Autowired
	HttpServletResponse response;
	public List<GoodsType> showAll(ModelMap model){
		List<GoodsType> typeList=gtService.showAll();
		model.put("typeList", typeList);
		return typeList;
	}

	//分页显示商品
	@RequestMapping(value="/show")
	public String showPage(String selName,Integer currPageNo,Integer typeId,ModelMap model){
		Map<String, Object> m=new HashMap<String,Object>();
		
		m.put("selName", selName);
		m.put("currPage", currPageNo);
		m.put("typeId", typeId);
		m=gService.showPage(m);
		PageInfo<Goods> pages=(PageInfo<Goods>)m.get("pages");
		model.put("pageInfo",pages);
		model.put("typeId", typeId);
		model.put("selName", selName);
		return "admin/Products_List";
	}
	
	//执行下架/上架类型
	@RequestMapping("/isSale")
	public String isSale(HttpSession session,String name,Integer currPageNo,Integer typeId,Integer Sellid,ModelMap model){
		gService.isSell(Sellid);
		Admininfo admin= (Admininfo)session.getAttribute("admin");
		int id=100;
		if(admin!=null){
			id=admin.getAdminid();
		}
		AppendContentToFile.fileLogPrint(id+"", "对"+Sellid+"号商品进行上架/下架");
		return this.showPage(name, currPageNo, typeId, model);
	}
	
	//执行修改
		@RequestMapping(value="/doUpdate",produces="application/json;charset=UTF-8")
		public @ResponseBody boolean doUpd(HttpSession session,int[] sid,String[] vid,String[] price,String[] stock,int goodsid,String title,String desc,Integer typeId,double truePrice,double salePrice,String isSale,String isHot,String isNew,String isBest,int goodsScore,String createtime,ModelMap model){
			
			
			vid=this.checkArraysNotNull(vid);
			price=this.checkArraysNotNull(price);
			GoodsWithBLOBs g=gService.selById(goodsid);
			if(sid!=null&&vid!=null&&price!=null&&stock!=null){
				List<Skus> skus=new  ArrayList<Skus>();
				int count=vid.length;
				int stockSum=0;
				for (int i = 0; i < count; i++) {
					Skus news=new Skus();
					news.setId(sid[i]);
					news.setSkuattr(Integer.parseInt(vid[i]));
					news.setPrice(new BigDecimal(price[i]));
					news.setStock(Integer.parseInt(stock[i]));
					stockSum+=Integer.parseInt(stock[i]);
					news.setGoodsid(goodsid);
					skus.add(news);
					
				}
				g.setStock(stockSum);
			}
			g.setGoddstitle(title);
			g.setGoodstypeid(new Long(typeId));
			g.setTrueprice(new BigDecimal(truePrice));
			g.setSaleprice(new BigDecimal(salePrice));
			if(isSale==null||isSale.equals("")){
				Byte b=0;
				g.setIssale(b);
			}else{
				Byte b=1;
				g.setIssale(new Byte(b));
			}
			if(isHot==null||isHot.equals("")){
				Byte b=0;
				g.setIshot(b);
			}else{
				Byte b=1;
				g.setIshot(b);
			}
			if(isNew==null||isNew.equals("")){
				Byte b=0;
				g.setIsnew(b);
			}else{
				Byte b=1;
				g.setIsnew(b);
			}
			if(isBest==null||isBest.equals("")){
				Byte b=0;
				g.setIsbest(b);
			}else{
				Byte b=1;
				g.setIsbest(b);
			}
			if(FileUDUtil.FILENAME.size()>=1){
				String fname=FileUDUtil.FILENAME.toString();
				int index1=fname.indexOf("[");
				int index2=fname.indexOf("]");
				fname=fname.substring(index1+1, index2);
				g.setGoodsimg(fname);
				g.setGoodsthums(FileUDUtil.FILENAME.get(0));
			}
			
			
			
			g.setGoodsscore(goodsScore);
			g.setGoodsdesc(desc);
			
			
			Admininfo admin= (Admininfo)session.getAttribute("admin");
			int id=100;
			if(admin!=null){
				id=admin.getAdminid();
			}
			AppendContentToFile.fileLogPrint(id+"", "对"+g.getGoodsid()+"号商品进行修改");
			
			
			
			return gService.doUpdate(g); 
		}
		//打开修改页面
		@RequestMapping("/openUpdate")
		public String openUpd(int DetailId,ModelMap model){
			GoodsWithBLOBs g=gService.selById2(DetailId);
			model.put("gd", g);
			String img=g.getGoodsimg();
			String[] imgs=img.split(",");
			model.put("imgs", imgs);
			List<Skus> skus=skuService.selByGoodId(g.getGoodsid());
			model.put("skus", skus);
			return "admin/member-add";
		}
		@RequestMapping("/openDetail")
		public String openDet(int DetailId,ModelMap model){
			GoodsWithBLOBs g=gService.selById2(DetailId);
			model.put("gd", g);
			String img=g.getGoodsimg();
			String[] imgs=img.split(",");
			model.put("imgs", imgs);
			List<Skus> skus=skuService.selByGoodId(g.getGoodsid());
			model.put("skus", skus);
			return "admin/product_detail";
		}
		@RequestMapping(value="/checkById",produces="application/json;charset=UTF-8")
		public @ResponseBody int checkById(int goodid){
			return skuService.selByGoodId(goodid).size();
		}
	
    public String[] checkArraysNotNull(String[] strs){
    	if(strs==null){
    		return null;
    	}
    	for (int i = 0; i < strs.length; i++) {
			String s = strs[i];
			if(s==null||s.equals("")){
				strs[i]="0";
			}
		}
    	return strs;
    }
	@RequestMapping(value="/doAdd",produces="application/json;charset=UTF-8")
	public @ResponseBody boolean doAdd(HttpSession session,HttpServletRequest request,String[] vid,String[] price,String[] stock,String title,String desc,Integer typeId,double truePrice,double salePrice,String isSale,String isHot,String isNew,String isBest,int goodsScore,ModelMap model){
		GoodsWithBLOBs g=new GoodsWithBLOBs();
		vid=this.checkArraysNotNull(vid);
		price=this.checkArraysNotNull(price);
		stock=this.checkArraysNotNull(stock);
		
		g.setGoddstitle(title);
		g.setGoodstypeid(new Long(typeId));
		g.setCollectnum(0);
		g.setLovenum(0);
		g.setTrueprice(new BigDecimal(truePrice));
		g.setSaleprice(new BigDecimal(truePrice));
		g.setSale(0);
		if(isSale==null||isSale.equals("")){
			Byte b=0;
			g.setIssale(b);
		}else{
			Byte b=1;
			g.setIssale(new Byte(b));
		}
		if(isHot==null||isHot.equals("")){
			Byte b=0;
			g.setIshot(b);
		}else{
			Byte b=1;
			g.setIshot(b);
		}
		if(isNew==null||isNew.equals("")){
			Byte b=0;
			g.setIsnew(b);
		}else{
			Byte b=1;
			g.setIsnew(b);
		}
		if(isBest==null||isBest.equals("")){
			Byte b=0;
			g.setIsbest(b);
		}else{
			Byte b=1;
			g.setIsbest(b);
		}
		g.setGoodsscore(goodsScore);
		if(desc!=null){
			g.setGoodsdesc(desc);
		}else{
			g.setGoodsdesc(" ");
		}
		g.setGoodsthums("");
		g.setCreatetime(new java.util.Date());
		g.setLasttime(new java.util.Date());
		/**
		 * 上传
		 */
		List<Skus> skus1=new  ArrayList<Skus>();
		if(vid!=null&&price!=null&&stock!=null){
			int count=vid.length;
			int stockSum=0;
			for (String s : stock) {
				stockSum+=Integer.parseInt(s);
			}
			g.setStock(stockSum);
		}else{
			g.setStock(0);
		}
			String fname=FileUDUtil.FILENAME.toString();
			int index1=fname.indexOf("[");
			int index2=fname.indexOf("]");
			fname=fname.substring(index1+1, index2);
			g.setGoodsimg(fname);
			if(fname.length()!=0){
				g.setGoodsthums(FileUDUtil.FILENAME.get(0));
			}
		gService.doInsert(g);
		List<Skus> skus=new  ArrayList<Skus>();
		if(vid!=null&&price!=null&&stock!=null){
			GoodsWithBLOBs g2=gService.selByName(title);
			int count=vid.length;
			for (int i = 0; i < count; i++) {
				Skus news=new Skus();
				news.setSkuattr(Integer.parseInt(vid[i]));
				news.setPrice(new BigDecimal(price[i]));
				news.setStock(Integer.parseInt(stock[i]));
				news.setGoodsid(g2.getGoodsid());
				skus.add(news);
			}
			skuService.addSkus(skus);
		}
		Admininfo admin= (Admininfo)session.getAttribute("admin");
		int id=100;
		if(admin!=null){
			id=admin.getAdminid();
		}
		AppendContentToFile.fileLogPrint(id+"", "添加了一件商品");
		return true;
	}
	@RequestMapping("/openDetails")
	public String openD(int id,ModelMap model){
		GoodsWithBLOBs g=gService.selById2(id);
		model.put("gd", g);
		String img=g.getGoodsimg();
		String[] imgs=img.split(",");
		model.put("imgs", imgs);
		return "admin/product_upd";
	}

	//批量删除
	@RequestMapping("/deleteGoods")
	public String deleteGoods(String[] goodsDeleter){
		List<Integer> goodsids=new ArrayList<Integer>();
		for (String j : goodsDeleter) {
			goodsids.add(Integer.parseInt(j));
		}
		gService.deleteGoods(goodsids);
		return "goods/show";
	}
	@RequestMapping("/openAdd")
	public String openAdd(ModelMap model){
		List<SkuAttrval> skuList=skuAS.showAll();
		model.put("skus", skuList);
		System.out.println("successsuccesssuccesssuccesssuccesssuccesssuccesssuccesssuccesssuccesssuccess");
		return "admin/picture-add";
	}
	
	
	
	
	/*****仇兴洲 前台购物********/
	@RequestMapping("/showGoodInfo")
	public String showGoodInfo(Integer goodsId,HttpSession session){
		
		//获取商品信息
		GoodsWithBLOBs good=gService.selById(goodsId);
		//截图图片
		good.setImgs(good.getGoodsimg().split(","));
		SkusExample example=new SkusExample();
		Criteria c=example.createCriteria();
		c.andGoodsidEqualTo(good.getGoodsid());
		good.setSkus(skusService.selectByExample(example));
		
		Users user = (Users) session.getAttribute("user");
		if (user != null) {
			Browfav brow = browfavService.selectByExample(user.getUserid(), goodsId, 1);
			if (brow == null || "".equals(brow)) {
				brow = new Browfav();
				brow.setUserid(user.getUserid());
				brow.setGoodsid(goodsId);
				brow.setGoodsnames(good.getGoddstitle());
				brow.setGoodsprice(good.getTrueprice());
				brow.setGoodsthums(good.getGoodsthums());
				brow.setLasttime(new java.util.Date());
				brow.setCreatetime(new java.util.Date());
				brow.setBrowfavtype((byte) 1);
				browfavService.insert(brow);

			} else {
				brow.setLasttime(new java.util.Date());
				browfavService.updateByPrimaryKey(brow);
			}
		}
		
		//获取 该商品下所有评论
		List<GoodsAppraises> appraises = goodsAppraisesService.selectByExampleWithBLOBs(goodsId);
		session.setAttribute("imgs",good.getImgs());
		session.setAttribute("good",good);
		session.setAttribute("appraises",appraises);
		return "redirect:/shopdetail.jsp";
	}
	
	
	/************** 陆严寒 ******************/
	// 根据条件查询商品
	@RequestMapping("/allList")
	public String allList(@RequestParam(value="currPageNo",defaultValue="1") Integer currPageNo,
			@RequestParam(value="pageSize",defaultValue="10") Integer pageSize,int goodstypeid, ModelMap model) {
		PageHelper.startPage(currPageNo, pageSize);
		List<Goods> list = gService.selectByExample(goodstypeid);
		model.put("goodstypeid", goodstypeid);
		PageInfo<Goods> pages=new PageInfo<Goods>(list,pageSize);
		model.put("pageInfo",pages);
		return "/list";
	}

	// 模糊查询
	@RequestMapping(value = "/like")
	public String selectByName(@RequestParam(value="currPageNo",defaultValue="1") Integer currPageNo,
			@RequestParam(value="pageSize",defaultValue="30") Integer pageSize,ModelMap model, String select) {
		PageHelper.startPage(currPageNo, pageSize);
		List<Goods> list = gService.selectByName(select);
		PageInfo<Goods> pages=new PageInfo<Goods>(list,pageSize);
		model.put("select", select);
		model.put("pageInfo",pages);
		return "/list";
	}

	// 商品和商品类别
	@RequestMapping(value = "/findHotType", produces = "application/json;charset=UTF-8")
	public @ResponseBody List<GoodsType> findHotType() {
		List<GoodsType> list = gService.findHotType();
		return list;
	}

	// 根据是否热销或是否精品或是否新品查询
	@RequestMapping(value = "/selectByIs")
	public String selectByIs(@RequestParam(value="currPageNo",defaultValue="1") Integer currPageNo,
			@RequestParam(value="pageSize",defaultValue="30") Integer pageSize,ModelMap model,
			@RequestParam(required=false) Integer is,
			@RequestParam(required=false) String seach,
			@RequestParam(value="flag",required=false) Integer flag,
			@RequestParam(value="minPrice",required=false) BigDecimal minPrice,
			@RequestParam(value="maxPrice",required=false) BigDecimal maxPrice,
			@RequestParam(value="goodstypeid",required=false) Integer goodstypeid) {
		PageHelper.startPage(currPageNo, pageSize);
		List<Goods> list=gService.selectByIs(is, seach, flag, minPrice, maxPrice, goodstypeid);
		PageInfo<Goods> pages=new PageInfo<Goods>(list,pageSize);
		model.put("minPrice", minPrice);
		model.put("maxPrice", maxPrice);
		model.put("goodstypeid", goodstypeid);
		model.put("select", seach);
		model.put("pageInfo",pages);
		return "list";
	}

	// 根据查询
	@RequestMapping(value = "/selectByPrice")
	public String selectByPrice(@RequestParam(value="currPageNo",defaultValue="1") Integer currPageNo,
			@RequestParam(value="pageSize",defaultValue="10") Integer pageSize,ModelMap model,
			@RequestParam(defaultValue="0",required=false) BigDecimal maxPrice,
			@RequestParam(defaultValue="0",required=false) BigDecimal minPrice,
			@RequestParam(required=false) Integer typeid,
			@RequestParam(required=false) String select) {
		PageHelper.startPage(currPageNo, pageSize);
		List<Goods> list = gService.selectByPrice(minPrice, maxPrice,typeid,select);
		PageInfo<Goods> pages=new PageInfo<Goods>(list,pageSize);
		model.put("minPrice", minPrice);
		model.put("maxPrice", maxPrice);
		model.put("typeid", typeid);
		model.put("select", select);
		model.put("pageInfo",pages);
		return "list";
	}
	
	//根据价格的降序和升序查询
	@RequestMapping(value = "/selectOrderByPrice")
	public String selectOrderByPrice(@RequestParam(value="currPageNo",defaultValue="1") Integer currPageNo,
			@RequestParam(value="pageSize",defaultValue="10") Integer pageSize,int flag,ModelMap model) {
		PageHelper.startPage(currPageNo, pageSize);
		List<Goods> list = gService.selectOrderByPrice(flag);
		PageInfo<Goods> pages=new PageInfo<Goods>(list,pageSize);
		model.put("pageInfo",pages);
		return "list";
	}
	
	@RequestMapping(value="/solr")
	public String findBySolr(@RequestParam(value="currPageNo",defaultValue="1") Integer currPageNo,
			@RequestParam(value="pageSize",defaultValue="30") Integer pageSize,ModelMap model,
			@RequestParam(required=false) Integer is,
			@RequestParam(required=false) String seach,
			@RequestParam(value="flag",required=false) Integer flag,
			@RequestParam(value="minPrice",required=false) BigDecimal minPrice,
			@RequestParam(value="maxPrice",required=false) BigDecimal maxPrice,
			@RequestParam(value="goodstypeid",required=false) Integer goodstypeid) throws UnsupportedEncodingException{
		if(seach!=null && !"".equals(seach)){
			seach=new String(seach.getBytes("iso8859-1"),"utf-8");
		}
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("goodstitle",seach);
		map.put("is",is);
		map.put("flag",flag);
		map.put("minPrice", minPrice);
		map.put("maxPrice", maxPrice);
		map.put("goodstypeid", goodstypeid);
		PageHelper.startPage(currPageNo,pageSize);
		List<Goods> list = gService.findBySolr(map);
		PageInfo<Goods> pages=new PageInfo<Goods>(list,pageSize);
		model.put("minPrice", minPrice);
		model.put("maxPrice", maxPrice);
		model.put("goodstypeid", goodstypeid);
		model.put("select",seach);
		model.put("pageInfo",pages);
		return "list";
	}
	/**
	 * 验证改订单下是否有商品已被下架
	 * @param orderid
	 * @return
	 */
	@RequestMapping(value = "/valIsSale/{orderid}", produces = "application/json;charset=UTF-8")
	public @ResponseBody boolean valIsSale(@PathVariable(value="orderid") Integer orderid){
		return gService.valIsSale(orderid);
	}
}